package cn.itzzx.lagou.netty.rpc;

import cn.itzzx.lagou.netty.rpc.provider.UserServiceImpl;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * 启动完springboot 后 ，启动Netty服务端
 * @author Martin
 * @date 2020-06-18
 * @see 1.0
 */
@Component
public class ServerInitialization implements CommandLineRunner {

    @Value("${zkAddr}")
    private String zkAddr;

    private CuratorFramework build;
    @Override
    public void run(String... args) throws Exception {
        //将IP及端口信息自动注册到Zookeeper
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);

        build = CuratorFrameworkFactory.builder()
                //zk 连接地址
                .connectString(zkAddr)
                //会话超时时间 50s
                .sessionTimeoutMs(50000)
                //连接超时时间 30 s
                .connectionTimeoutMs(30000)
                //失败重试机制
                .retryPolicy(retryPolicy)
                .build();
        build.start();
        //创建一个临时节点 127.0.0.1 内容为端口号  /task-01/127.0.0.1
        build.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/task-01/127.0.0.1:8090","127.0.0.1:8090".getBytes());
        UserServiceImpl.startServer("127.0.0.1",8090);
    }

    @PreDestroy
    public void destory() throws Exception {
        build.delete().forPath("/task-01/127.0.0.1:8090");
    }

}
